package com.thb.pay.core.interceptor;

import com.thb.pay.core.annotation.LoginRequired;
import com.thb.pay.core.enums.Action;
import com.thb.pay.core.enums.ExceptionEnum;
import com.thb.pay.core.exception.RRException;
import com.thb.pay.core.jwt.JwtUtils;
import com.thb.pay.core.utils.Constant;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登入校验
 */
@Slf4j
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader(Constant.HEADER_TOKEN);
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        /**
         *  检查是否有 LoginRequired 注释，Action.Skip
         */
        if (method.isAnnotationPresent(LoginRequired.class)) {
            LoginRequired required = method.getAnnotation(LoginRequired.class);
            if (required.value().equals(Action.Skip)) {
                return true;
            }
            if (StringUtils.isEmpty(token)) {
                throw RRException.build(ExceptionEnum.TOKEN_EXPIRE);
            }
            if (jwtUtils != null) {
                Claims claims = jwtUtils.getClaimByToken(token);
                if (claims == null) {
                    throw RRException.build(ExceptionEnum.LOGIN_ERROR);
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }

}